package com.xbongbong.rule.symbol;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.rule.symbol.base.AbstractSymbol;
import com.xbongbong.saas.constant.StringConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

/**
 * 数值比较判断
 *
 * @author zheng.li
 **/
@Slf4j
public class NumberCompareSymbol extends AbstractSymbol {

    @Override
    public boolean operation() {
        if (StringUtils.isEmpty(value.toString()) || conditionValueList.isEmpty()) {
            return false;
        }

        if (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
            //子表单
            JSONArray arrayValue = factJson.getJSONArray(attr);
            if (CollectionsUtil.isNotEmpty(arrayValue)) {
                return arrayValue.stream().anyMatch(v -> compare(v.toString()));
            }
        } else {
            //其他
            return compare(value.toString());
        }
        return false;
    }

    private boolean compare(String realValue) {
        BigDecimal valueDecimal;
        BigDecimal startDecimal;
        try {
            valueDecimal = new BigDecimal(realValue);
            startDecimal = new BigDecimal(conditionValue.toString());
        } catch (Exception e) {
            log.error("转成BigDecimal错误", e);
            return false;
        }
        switch (conditionEnum) {
            case LESSTHAN:
                return valueDecimal.compareTo(startDecimal) < 0;
            case LESSEQUAL:
                return valueDecimal.compareTo(startDecimal) < 1;
            case GREATERTHAN:
                return valueDecimal.compareTo(startDecimal) > 0;
            case GREATEREQUAL:
                return valueDecimal.compareTo(startDecimal) > -1;
            default:
                break;
        }
        return false;
    }
}
